﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HWmanagementClient.Models;
using HWmanagementClient.HWManager;
using HWmanagementClient.Codes;
using System.IO;

namespace HWmanagementClient.Controllers
{
    public class TeacherController : Controller
    {
        protected override void ExecuteCore()
        {
            try
            {
                ViewBag.Rank = HWmanagementClient.Codes.Site.GetAuthUserRank(Request, User);
            }
            catch
            {
                ViewBag.Rank = -1;
            }
            base.ExecuteCore();
        }


        //
        // GET: /Teacher/


        #region FULL DONE

        private TeacherHomeworks loadhomeworks()
        {
            ManagerClient proxy = new ManagerClient();
            var hwk = proxy.getSubjects(Site.GetAuthUserCode(Request, User));


            TeacherHomeworks model = new TeacherHomeworks()
            {
                Subjects = hwk.Select(
                    (sm) => SubjectClientModel.fromWCFmodel(sm)
                    ).ToList()
            };

            foreach (var item in model.Subjects)
            {
                item.courses = proxy.getCourses(item.neptun).ToList();
            }

            return model;
        }

        //Grade and Index page are uses too
        [HttpPost]
        public ActionResult GetGroupUsers(int id)
        {
            ManagerClient proxy = new ManagerClient();

            TeacherHomeworks model = new TeacherHomeworks();
            try
            {
                model.users = proxy.getUsersOnHw(id).ToList();
            }
            catch { }
            return Json(model);
        }

        #region Index Page

        public ActionResult Index()
        {
            return View(loadhomeworks());
        }

        [HttpPost]
        public ActionResult Index(HttpPostedFileBase file, FormCollection formCollection, TeacherHomeworks model)
        {
            var course = -1;
            try
            {
                course = int.Parse(formCollection["courseid"]);
            }
            catch
            {
                ViewBag.Succeeded = false;
                return View(loadhomeworks());
            }
            var neptun = Site.GetAuthUserCode(Request, User);
            string path = "";
            // Verify that the user selected a file
            if (file != null && file.ContentLength > 0)
            {
                // extract only the fielname
                var fileName = Path.GetFileName(file.FileName);
                // store the file inside ~/App_Data/uploads folder
                DirectoryInfo dir = new DirectoryInfo(Path.Combine(Server.MapPath("~/App_Data/HWmanager/uploads/" + neptun)));
                if (!dir.Exists)
                {
                    dir.Create();
                }
                path = Path.Combine(Server.MapPath("~/App_Data/HWmanager/uploads/" + neptun), fileName);
                try
                {
                    file.SaveAs(path);
                }
                catch
                {
                    ViewBag.Succeeded = false;

                    // redirect back to the index action to show the form once again
                    return View();
                }
            }

            ManagerClient proxy = new ManagerClient();
            HomeworkModel hwm = new HomeworkModel()
            {
                courseid = course,
                userid = neptun,
                shortdesc = model.newhw.shortdesc,
                title = model.newhw.title,
                deadline = model.newhw.deadline
            };

            FileModel fm = new FileModel()
            {
                name = path
            };

            try
            {
                proxy.postNewHomework(hwm, fm);
            }
            catch
            {
                ViewBag.Succeeded = false;
            }

            ViewBag.Succeeded = true;

            // redirect back to the index action to show the form once again
            return View(loadhomeworks());
        }

        [HttpPost]
        public ActionResult GetHomeworks(int id)
        {
            ManagerClient proxy = new ManagerClient();

            var hws = proxy.getTeacherHomeworks(Site.GetAuthUserCode(Request, User), id);

            TeacherHomeworks model = new TeacherHomeworks() { Homeworks = hws.ToList().Select((hm) => HomeworkClientModel.fromWCFmodel(hm)).ToList() };
            return Json(model);
        }

        [HttpPost]
        public ActionResult GetStudents(int id)
        {
            ManagerClient proxy = new ManagerClient();

            var model = proxy.getAllUser();

            //var model2 = model.ToList();

            //foreach (var item in model2)
            //{
            //    var subs = proxy.getSubjects(item.Neptun).Select((sm) => sm.neptun).ToList();
                
            //}

            var q = (from m in model
                     where m.Rank == 2
                     select string.Format("{0} ({1})", m.Name, m.Neptun))
                    .ToList();

            return Json(q);
        }

        [HttpPost]
        public ActionResult DeleteHomework(int id)
        {

            bool succ = true;

            ManagerClient proxy = new ManagerClient();

            try
            {
                proxy.deleteHomework(id);
            }
            catch
            {
                succ = false;
            }

            return Json(succ);
        }

        [HttpPost]
        public ActionResult AddToGroup(FormCollection data)
        {
            bool succ = true;
            var user = data["user"];
            var gid = int.Parse(data["gid"]);
            var hid = int.Parse(data["hid"]);
            var neptun = user.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries).Last();

            ManagerClient proxy = new ManagerClient();

            try
            {
                proxy.addStudentToGroup(neptun, gid);
            }
            catch (Exception)
            {
                succ = false;
            }

            return Json(succ);
        }

        #endregion

        #region Subjects Page

        public ActionResult Subjects()
        {
            ManagerClient proxy = new ManagerClient();

            TeacherHomeworks model = new TeacherHomeworks();
            model.allSubject = proxy.getAllSubjects().Select((sm) => SubjectClientModel.fromWCFmodel(sm)).ToList();
            return View(model);
        }

        [HttpPost]
        public ActionResult DeleteTeacher(FormCollection data)
        //public ActionResult AddToGroup(GroupPost form)
        {
            var user = data["user"];
            var hid = data["subject"];
            var neptun = user.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries).Last();

            ManagerClient proxy = new ManagerClient();

            try
            {
                proxy.removeTeacher(user, hid);
                return Json(true);
            }
            catch
            {
                return Json(false);
            }
        }

        [HttpPost]
        public ActionResult AddTeacher(FormCollection data)
        //public ActionResult AddToGroup(GroupPost form)
        {
            var user = data["user"];
            var hid = data["subject"];
            var neptun = user.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries).Last();

            ManagerClient proxy = new ManagerClient();

            try
            {
                proxy.addTeacher(neptun, hid);
                return Json(true);
            }
            catch
            {
                return Json(false);
            }
        }

        [HttpPost]
        public ActionResult GetTeachers()
        {
            ManagerClient proxy = new ManagerClient();

            var model = proxy.getAllUser();

            var q = (from m in model
                     where m.Rank == 1
                     select string.Format("{0} ({1})", m.Name, m.Neptun))
                    .ToList();

            return Json(q);
        }

        [HttpPost]
        public ActionResult GetSubTeach(string id)
        {
            ManagerClient proxy = new ManagerClient();
            var hws = proxy.getTeachers(id).ToList();
            

            TeacherHomeworks model = new TeacherHomeworks() { users = hws };
            return Json(model);
        }

        #endregion

        #region Grades Page

        public ActionResult Grades()
        {
            return View(loadhomeworks());
        }

        [HttpPost]
        public ActionResult GetGrade(int id)
        {
            ManagerClient proxy = new ManagerClient();

            var hws = proxy.getTeacherHomeworks(Site.GetAuthUserCode(Request, User), id);

            TeacherHomeworks model = new TeacherHomeworks() { Homeworks = hws.ToList().Select((hm) => HomeworkClientModel.fromWCFmodel(hm)).ToList() };
            return Json(model);
        }

        #endregion

        #endregion


        





        [HttpPost]
        public ActionResult Grades(TeacherHomeworks model, FormCollection formCollection)
        {
            var hwid = int.Parse(formCollection["hwid"]);
            var neptun = formCollection["userid"];

            ManagerClient proxy = new ManagerClient();
            try
            {
                var gr1 = proxy.viewResult(hwid, neptun);

                try
                {
                    proxy.modifyResult(new ResultModel()
                    {
                        comment = model.newresult.comment,
                        grade = model.newresult.grade,
                        homeworkid = hwid,
                        userid = neptun,
                        id = gr1.id
                    });
                }
                catch
                {
                    ViewBag.Succeeded = false;
                }
            }
            catch
            {
                proxy = new ManagerClient();

                try
                {
                    proxy.writeResult(new ResultModel()
                        {
                            comment = model.newresult.comment,
                            grade = model.newresult.grade,
                            homeworkid = hwid,
                            userid = neptun
                        });
                }
                catch
                {
                    ViewBag.Succeeded = false;
                }
            }

            return View(loadhomeworks());
        }

        [HttpPost]
        public ActionResult GetUFiles(FormCollection data)
        {

            var user = data["userid"];
            var hw = int.Parse(data["hwid"]);

            ManagerClient proxy = new ManagerClient();

            TeacherHomeworks model = new TeacherHomeworks();
            try
            {
                var last = proxy.getFiles(hw, user, true).Last();
                model.files = proxy.getFiles(hw, user, false).Select((fm) => FileClientModel.fromWCFmodel(fm, last)).ToList();
            }
            catch {
                model.files = new List<FileClientModel>();
            }
            
            return Json(model);
        }

        [HttpPost]
        public ActionResult DelFromGroup(FormCollection data)
        {
            bool succ = true;
            var user = data["user"];
            var gid = int.Parse(data["gid"]);
            var neptun = user.Split(new[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries).Last();

            ManagerClient proxy = new ManagerClient();

            try
            {
                proxy.removeStudentFromGroup(neptun, gid);
            }
            catch (Exception)
            {
                succ = false;
            }

            return Json(succ);
        }

        [HttpPost]
        public ActionResult GetGGrade(FormCollection data)
        {
            var user = data["userid"];
            var hw = int.Parse(data["hwid"]);

            ManagerClient proxy = new ManagerClient();
            ResultModel gr = new ResultModel();
            try
            {
                gr = proxy.viewResult(hw, user);
            }
            catch
            {
                gr.comment = "";
                gr.grade = 0;
            }

            return Json(new { grade = gr.grade, comment = gr.comment });
        }

        [HttpPost]
        public ActionResult GetTeachers2()
        {
            ManagerClient proxy = new ManagerClient();

            var model = proxy.getAllUser();

            var q = (from m in model
                     select string.Format("{0}: {1} ({2})",m.Rank == 1 ? "oktató" : "halglató", m.Name, m.Neptun))
                    .ToList();

            return Json(q);
        }

        public ActionResult Logs()
        {
            ManagerClient proxy = new ManagerClient();
            var model = proxy.getLogs().ToList();

            List<LogClientModel> mod = new List<LogClientModel>();

            foreach (var item in model)
            {
                var usr = proxy.GetLoggedInUser(item.userid);
                mod.Add(new LogClientModel()
                {
                    action = item.action,
                    date = item.date,
                    user = usr.Name + " ("+usr.Neptun+")"
                });
            }

            return View(mod);
        }

    }
}
